<?php

/**
 * License
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 **/

/**
 * MightMedia startinis puslapis
 *
 * @author Vytenis Kučiauskas (FDisk)
 * @copyright 2008 CodeRS
 * @license http://opensource.org/licenses/lgpl-license.php GNU Lesser General Public License
 **/
 
ob_start ();
header("Cache-control: public");
header("Content-type: text/html; charset=utf-8");
header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
if (!isset($_SESSION)) session_start();

//kad rodytu per kiek laiko sugeneravo koda
$m1 = explode(" ", microtime());$stime = $m1[1] + $m1[0];

//Iterpiam nustatymu faila jei ne perkialiam i instaliacija
if (is_file('priedai/conf.php')) { include_once("priedai/conf.php"); }
elseif (is_file('setup.php')) { header('location: setup.php'); }
else { die(klaida('Sistemos klaida','Atsiprašome svetainė neįdiegta. Trūksta sisteminių failų.')); }
if (!defined('SETUP') || !SETUP) { header('location: setup.php'); }
include_once("priedai/header.php");

/* Puslapiu aprasymas */
if (isset($url['id']) && !empty($url['id']) && isnum($url['id'])) { $id = (int)$url['id']; } else { $id = 0; }
if (isset($id) && isnum($id) && $id > 0) {
    switch ($id) {
    	//Naujam puslapiui irasome skaiciuka (unikalu) ir nurodome puslapi be (.php) galunes. Paciam gale (break;)
       case 5: { $page = "puslapiai/apie"; break; }
       case 6: { $page = "puslapiai/siustis"; break; }
       //case 7: { $page = "puslapiai/apie"; break; }
       case 8: { $page = "puslapiai/duk"; break; }
       case 9: { $page = "puslapiai/knyga"; break; }
       //case 15: { $page = "puslapiai/dj/index"; break; }
       case 25: { $page = "puslapiai/frm"; break; }
       case 27: { $page = "puslapiai/zaidimai"; break; }
       case 40: { $page = "puslapiai/online"; break; }
       case 41: { $page = "puslapiai/reg"; break; }
       case 42: { $page = "puslapiai/slaptazodzio_priminimas"; break; }
       case 43: { $page = "puslapiai/logout"; break; }
       case 44: { $page = "puslapiai/edit_user"; break; }
       case 45: { $page = "puslapiai/pm"; break; }
       case 46: { $page = "puslapiai/dievai/index"; admin_login(); break; }
       case 47: { $page = "puslapiai/view_user"; break; }
       case 49: { $page = "puslapiai/deze"; break; }
       case 50: { $page = "puslapiai/naujienos"; break; }
       default: { $page = "puslapiai/naujienos"; break; }
    }
}
else { $page = "puslapiai/naujienos"; }
if (!file_exists($page.'.php')) { $page = "puslapiai/klaida"; }

/**
 * Prisijungimas ir vartotojo valdymas
 */
##################### Auto Atjungimas nuo sistemos ########################
if (isset($_SESSION['username']) && isset($_SESSION['password'])) {
	$linfo = mysql_fetch_assoc(mysql_query1("SELECT levelis FROM `".LENTELES_PRIESAGA."users` WHERE nick=" . escape($_SESSION['username']) ." AND pass=" . escape($_SESSION['password']) ." LIMIT 1"));
	if (!empty($linfo['levelis'])) { define("LEVEL",$linfo['levelis']); } // Priskiriam leveli = vartotojo lygi
	else {
		unset($_SESSION['username'],$_SESSION['password'],$_SESSION['id'],$_SESSION['lankesi']);	// Isvalom sesija
		//session_unset();
		//session_destroy();
		setcookie ("user", "", time() - 3600); // Sunaikinam sesija
	}
	unset($linfo);
}
elseif (isset($_COOKIE['user']) && !empty($_COOKIE['user'])) {
	$user_id = explode(".",$_COOKIE['user'],2);
	if (isnum($user_id['0'])) { $user_pass = $user_id['1']; $user_id = $user_id['0']; }
	$linfo = mysql_fetch_assoc(mysql_query1("SELECT levelis,pass,nick,login_data FROM `".LENTELES_PRIESAGA."users` WHERE id=" . escape((int)$user_id) ." LIMIT 1"));
	if (!empty($linfo['levelis']) && $linfo['levelis']>0 && md5($slaptas.getip().$linfo['pass']) === $user_pass) {
		mysql_query1("UPDATE `".LENTELES_PRIESAGA."users` SET `login_data` = NOW(), `ip` = INET_ATON(".escape($_SERVER['REMOTE_ADDR']).") WHERE `users`.`id` =" . escape($user_id) ." LIMIT 1");
		$_SESSION['username'] = $linfo['nick'];
		$_SESSION['password'] = $linfo['pass'];
		$_SESSION['id'] = $user_id;
		$_SESSION['lankesi'] = $linfo['login_data'];
		define("LEVEL",$linfo['levelis']);
	} // Priskiriam leveli = vartotojo lygi
	else {
		mysql_query1("INSERT INTO `".LENTELES_PRIESAGA."logai` (`action` ,`time` ,`ip`) VALUES (".escape("Klaidingas sausainis: UserID: ".$user_id." Pass: ".$user_pass).", NOW(), INET_ATON(".escape(getip())."))");
		unset($_SESSION['username'],$_SESSION['password'],$_SESSION['id'],$_SESSION['lankesi']);	// Isvalom sesija
		//session_unset();
		//session_destroy();
		setcookie ("user", "", time() - 3600); // Sunaikinam sesija
	}
	unset($linfo);

}

##################### Jei svetaine uzdaryta remontui ir jei jungiasi ne administratorius ###
if ($conf['Palaikymas'] == 1) {
	if (!defined("LEVEL") || LEVEL < 30) { redirect("remontas.php"); }
}

##################### Prisijungimas prie sistemos ########################
if (isset($_POST['action']) && $_POST['action'] == 'prisijungimas') {

	//Jeigu prisijungimo bandymai nevirsyjo limito
	if (!isset($_SESSION['login_error']) || $_SESSION['login_error'] <= $conf['Bandymai']) {

		$strUsername = htmlspecialchars($_POST['vartotojas']);	// Vartotojo vardas
		$strPassword = md5($_POST['slaptazodis']);	// Slaptazodis
		$linfo = mysql_fetch_assoc(mysql_query1("SELECT `id`, `login_data`, `nick`, `pass`, `levelis` FROM `".LENTELES_PRIESAGA."users` WHERE nick=" . escape($strUsername) ." AND pass='" . $strPassword ."' LIMIT 1"));

		if (!empty($linfo) && $strPassword === $linfo['pass']) {
			$_SESSION['username'] = input($linfo['nick']);
			$_SESSION['password'] = $strPassword;
			$_SESSION['id'] = $linfo['id'];
			$_SESSION['lankesi'] = $linfo['login_data'];
			define("LEVEL", $linfo['levelis']);
			mysql_query1("UPDATE `".LENTELES_PRIESAGA."users` SET `login_data` = NOW(), `ip` = INET_ATON(".escape(getip()).") WHERE `id` ='" . $linfo['id'] ."' LIMIT 1");
			if (isset($_POST['Prisiminti']) && $_POST['Prisiminti'] == 'on') {
				setcookie("user", $_SESSION['id'].".".md5($slaptas.getip().$_SESSION['password']), time()+60*60*24*30);
			}
		}
		else {
			mysql_query1("INSERT INTO `".LENTELES_PRIESAGA."logai` (`action` ,`time` ,`ip`) VALUES (".escape("Klaida loginantis: User: ".$strUsername." Pass: ".$_POST['slaptazodis']).",NOW(),INET_ATON(".escape($_SERVER['REMOTE_ADDR'])."));");
			$strError = 'Klaidingi prisijungimo duomenys'; 
			isset($_SESSION['login_error'])?$_SESSION['login_error']++:$_SESSION['login_error']=1;
		}
		unset($linfo,$strUsername,$strPassword);
	}
	else { 
		$strError = "<b>Prisijungimas draudžiamas</b>.<br />Prisijungti galėsite praėjus <b><span id='sekundes'>".ini_get('session.cache_expire')."</span></b><script>startCount();</script>s. Jei pamiršote savo slaptažodį spauskite <a href='?id,42'>ČIA</a>"; 
    }
}

//Tikrinam ar setup.php failas pašalintas. Saugumo sumetimais
if (is_file('setup.php') && defined('LEVEL') && LEVEL == 30 && !@unlink('setup.php')) { klaida('Dėmesio','<h3>Neištrintas setup.php failas.</h3> Tai saugumo spraga. Prašome pašalinkite šį failą iš serverio arba pakeiskite jo pavadinimą.'); }

include_once('stiliai/'.$conf['Stilius'].'/index.php');
?>